package com.hujifang.elasticsearch.utils;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Http客户端<br/>
 * @author hujifang
 */
public class HttpUtil {

    public static void main(String[] args)  throws Exception{
        String result=sendHttpPost("http://bus.devel.oneplus.cn/cs/remote/customServFacade.json",
                "{\"method\":\"findKnowledge\",\"jsonrpc\":2,\"params\":[{\"storeId\":2}],\"id\":\"z8wh9ozJ8rur7yVz\"}", "UTF-8", true);
        System.err.println(result);
    }

    public class HttpMethodType{
        public final static String POST="POST";
        public final static String GET="GET";
        public final static String PUT="PUT";
    }
    
    /**
     * 发送post请求 <br/>
     * @param url 请求url
     * @param parameters 请求参数
     * @param charset 编码
     * @param pretty 是否换行
     * @author HuJiFang
     */
    public static String sendHttpPost(String url,String parameters, String charset, boolean pretty) throws Exception{
    	// 构造HttpClient的实例
        HttpClient httpClient = new HttpClient();
        PostMethod method = new PostMethod(url);
        StringBuilder stringBuilder = new StringBuilder();
        try{
        	RequestEntity requestEntity=new StringRequestEntity(parameters,"application/json", charset);
    		method.setRequestEntity(requestEntity);	
			// 执行Method
            int statusCode = httpClient.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                // 读取内容
                InputStream responseBody = method.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(responseBody, charset));
                String tempbf;
                while ((tempbf = br.readLine()) != null) {
                    if(pretty){
                        stringBuilder.append(tempbf).append(System.getProperty("line.separator"));
                    }else{
                        stringBuilder.append(tempbf);
                    }
                }
                br.close();
            }else{
            	String responseBody=method.getResponseBodyAsString();
            	responseBody= JSONUtils.toJsonStr(responseBody);
            	throw new IllegalStateException("执行HTTP post request请求时状态异常,statusCode="+statusCode+",responseBody="+responseBody);
            }
		}catch (URIException e) {
            throw new IllegalStateException("执行HTTP post request请求时，编码查询字符串“" + parameters + "”发生异常！", e);
        } catch (Exception e) {
            throw new IllegalStateException("执行HTTP post request请求" + url + "时，发生异常！", e);
		}finally {
            method.releaseConnection();
        }
        return stringBuilder.toString();
    }

    /**
     * 发送http请求
     * @param requestMethod 请求方式
     * @param url 请求url
     * @param parameters 请求参数
     * @param charset 编码
     * @param pretty 是否换行
     * @author HuJiFang
     */
    public static String sendHttpRequest(String requestMethod, String url,String parameters, String charset, boolean pretty) throws Exception {
        // 构造HttpClient的实例
        HttpClient httpClient = new HttpClient();
        HttpMethod method = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            if (HttpMethodType.POST.equalsIgnoreCase(requestMethod)) {
                method = new PostMethod(url);
                if (StringUtils.isNotBlank(parameters)) {
                    RequestEntity requestEntity=new StringRequestEntity(parameters,"application/json", charset);
                    ((PostMethod)method).setRequestEntity(requestEntity);
                }
            } else if (HttpMethodType.GET.equalsIgnoreCase(requestMethod)) {
                method = new GetMethod(url);
                if (StringUtils.isNotBlank(parameters)) {
                    method.setQueryString(parameters);
                }
            }else if (HttpMethodType.PUT.equalsIgnoreCase(requestMethod)){
                method = new PutMethod(url);
                if (StringUtils.isNotBlank(parameters)) {
                    RequestEntity requestEntity=new StringRequestEntity(parameters,"application/json", charset);
                    ((PutMethod)method).setRequestEntity(requestEntity);
                }
            }else{
            	throw new IllegalStateException("The http client util can not support this request method of "+requestMethod);
            }
			// 使用系统提供的默认的恢复策略
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());

            // 执行Method
            int statusCode = httpClient.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                // 读取内容
                InputStream responseBody = method.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(responseBody, charset));
                String tempbf;
                while ((tempbf = br.readLine()) != null) {
                    if(pretty){
                        stringBuilder.append(tempbf).append(System.getProperty("line.separator"));
                    }else{
                        stringBuilder.append(tempbf);
                    }
                }
                br.close();
            }
        } catch (URIException e) {
            throw new IllegalStateException("执行HTTP "+requestMethod+" request请求时，编码查询字符串“" + parameters + "”发生异常！", e);
        } catch (Exception e) {
            throw new IllegalStateException("执行HTTP "+requestMethod+" request请求" + url + "时，发生异常！", e);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
        return stringBuilder.toString();
    }
}

